<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索模块，添加用户 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="users" style="width: 100%" stripe border>
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mg_state" label="用户状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changUserState(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)" size="mini"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteUserById(scope.row.id)"
              size="mini"></el-button>
            <el-tooltip class="item" effect="dark" content="用户权限管理" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"
                @click="showsetDialogVisible(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">

      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="addDialogClosed" width="50%">
      <el-form :model="addForm" :rules="addRuleForm" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="email">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户信息对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" @close="editDialogClosed" width="50%">
      <el-form :model="editForm" :rules="editRuleForm" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置角色对话框 -->
    <el-dialog title="提示" :visible.sync="setDialogVisible" width="30%" @close="setDialogClose">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色名：{{ userInfo.role_name }}</p>
        <p>
          <el-select v-model="selectId" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
export default {
  data() {
    //自定义验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!regEmail.test(value)) {
        return callback(new Error('请输入合法的邮箱'));
      }
      callback()
    }
    // 自定义验证手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^([0|86|17951])?(13[0-9]|15[123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (!regMobile.test(value)) {
        return callback(new Error('请输入合法的手机号'));
      }
      callback()
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        // 当前每页显示多少条
        pagesize: 2
      },
      total: 0,
      users: [],
      // 控制添加用户对话框
      addDialogVisible: false,
      // 控制编辑用户信息对话框
      editDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addRuleForm: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }

        ]
      },
      editForm: {},
      editRuleForm: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制角色对话框
      setDialogVisible: false,
      // 保存角色信息
      userInfo: [],
      // 全部角色列表
      roleList: [],
      // 被选中的id
      selectId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", { params: this.queryInfo });
      if (res.meta.status !== 200) return this.$message.error("获取用户列表失败")
      this.users = res.data.users
      this.total = res.data.total
    },
    // 每页显示多少天数据
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 当前页码
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 修改用户状态
    async changUserState(newInfo) {
      const { data: res } = await this.$http.put(`users/${newInfo.id}/state/${newInfo.mg_state}`)
      console.log(res)
    },
    // 监听表单关闭重置数据
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定之前的表单验证操作，添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error("添加用户失败")
        this.$message.success("添加用户成功")
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 编辑用户信息
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error("查询用户信息失败")
      }
      this.editForm = res.data
    },
    // 修改用户信息
    async editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) return this.$message.error("修改用户信息失败")
        this.$message.success("修改用户信息成功")
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 监听修改表单关闭，重置数据
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    async deleteUserById(id) {
      const confirmResult = await this.$confirm('是否永久删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户点击确定，返回confirm
      // 点击去取消，返回cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info("取消删除用户操作！")
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败！")
      }
      this.$message.success("删除用户成功！")
      this.getUserList()
    },
    async showsetDialogVisible(roleItem) {
      this.userInfo = roleItem
      this.setDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！")
      }
      this.roleList = res.data
    },
    async setRole() {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectId })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.setDialogVisible = false
      this.getUserList()
    },
    setDialogClose() {
      this.selectId = ''
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  box-shadow: 0 1px 1px rgba(1, 1, 1, 0.12);

  .el-table {
    margin-top: 20px;
  }
}
</style>